g_count = 5
g_nodes = {}
g_samples = {}
originFrames = {}
drawModel = nil
totalframeIndex = 0 --前指针
oldFrameIndex = 0 --后指针

totalNodesIndex = 0 --前指针
oldNodesIndex = 0 --后指针

triggerTime = 0
triggerIndex = -1
function initialize(scene)
  local snapShot = getCurrentSnapshot(scene,1.0)
  addNodeAndRelease(scene, KuruClearNode.create(Vector4.create(0.0, 0.0, 0.0, 0.0)))
  local g_segNode = createSegNode(snapShot)
  addNodeAndRelease(scene,g_segNode)
  local snapShot2 = getCurrentSnapshot(scene,1.0)
  --g_clearNode = addNodeAndRelease(scene, KuruClearNode.create(Vector4.create(0.0, 0.0, 0.0, 0.0)))
  -- createSegNode(scene,nil,snapShot)
  -- local snapShot2 = getCurrentSnapshot(scene,1.0)

  -- local g_framebuffer=  addNodeAndRelease(scene, KuruFrameBufferNode.create())
  -- --local g_bgNode = addChildAndRelease(g_framebuffer, KuruBackgroundImageNode.createFromSampler(snapShot:getSampler(), BlendMode.None))
  -- addChildAndRelease(g_framebuffer, KuruClearNode.create(Vector4.create(0.0, 0.0, 0.0, 0.0)))
  -- local g_segNode = createSegNode(snapShot)
  -- addChildAndRelease(g_framebuffer,g_segNode)
  -- local g_SnapNode = addChildAndRelease(g_framebuffer, KuruSnapshotNode.create())
  
  -- local floatNode1 = KuruFloatingImageNode.createFromSampler(g_framebuffer:getSampler(),-1,-1,1,1,BlendMode.None)
  -- addNodeAndRelease(scene,floatNode1)

  local g_displayFragNode = addNodeAndRelease(scene, getFragmentShader("display.frag"))
  g_displayFragNode:setChannel0(snapShot:getSampler())


  local frameMesh = Mesh.createQuadFullscreen()
  drawModel = Model.create(frameMesh)
  frameMesh:release()

  local material = Material.createWithShaderFile("res/shaders/passthrough.vert", "res/shaders/passthrough.frag", Nil)
  material:getParameter("u_worldViewProjectionMatrix"):setMatrix(Matrix.identity())
  material:getParameter("u_texture"):setSampler(snapShot2:getSampler())
  drawModel:setMaterial(material, -1)

  -- for i=1,g_count do
  --   local tempSampler = snapShot:getSnapshot()
  --   local bufferSampler  = TextureSampler.createWithTexture(tempSampler:getTexture())
  --  --bufferSampler:setWrapMode(TextureWrap.CLAMP, TextureWrap.CLAMP)
  --   local floatNode1 = KuruFloatingImageNode.createFromSampler(bufferSampler,-1,-1,1,1,BlendMode.None)
  --   addNodeAndRelease(scene,floatNode1)
  --   g_nodes[i] = floatNode1
  --   g_samples[i] = bufferSampler
  -- end

end

function frameReady(scene, elapsedTime)
 
  local index = math.floor(triggerTime/50)
  print("indexindex"..index)
  
  if triggerIndex ~= index then
    print("triggerSlowmotion")
   triggerSlowmotion(index,scene)
    triggerIndex = index
  end
  triggerTime = triggerTime + elapsedTime

end

function triggerSlowmotion(frameIndex, scene)

 -- local index = frameIndex % 1 --控制刷新率

 -- if totalframeIndex-oldFrameIndex < 10 then --总共50帧,使用队列控制
    local state = FrameBufferBindingState.create()
    local frameBuffer = FrameBuffer.create("STORED_FB_1", math.floor(scene:getResolution().x), math.floor(scene:getResolution().y), TextureFormat.RGBA)
    frameBuffer:bindWithViewport(true)
    drawModel:draw()
    state:restore()
    totalframeIndex = totalframeIndex+1
    originFrames[totalframeIndex] = frameBuffer
   -- print("originFramesoriginFrames"..#originFrames)
 -- end
  -- if(totalframeIndex>10) then
     -- for i=1,1 do
        local slowFrameBuffer = getFrameBufferWithIndex(totalframeIndex) --取到第一帧
        local frameSampler = TextureSampler.createWithTexture(slowFrameBuffer:getRenderTarget(0):getTexture())
        if frameSampler ~= nil then
        -- if g_node==nil then
          local  g_node = createBGNodeWithSampler(frameSampler)
            totalNodesIndex = totalNodesIndex+1
            g_nodes[totalNodesIndex] = g_node
            addNodeAndRelease(scene,g_node)
        -- end
            if totalNodesIndex-oldNodesIndex>20 then
                oldNodesIndex = oldNodesIndex+1
                scene:removeNode(g_nodes[oldNodesIndex])
                g_nodes[oldNodesIndex] = nil
                
            end
            frameSampler:release()
        else
          print("frameSampler nil")
        end
       
      --end
 
      if  totalframeIndex>15  then
        removeBufferWithIndex(oldFrameIndex)
        oldFrameIndex = oldFrameIndex+1
      end
   
    end 

--end

function getFrameBufferWithIndex(index) --得到第一个
 
  if originFrames[index] ~= nil then
    return originFrames[index]
  end
  return nil
end

function removeBufferWithIndex(index) --移除第一个
  
  if originFrames[index] ~= nil then
    originFrames[index]:release()
    originFrames[index] = nil
    return
  end

end

function clearBuffers() --清除所有buffers
  for i = 1, #originFrames do
    if originFrames[i] ~= nil then
      originFrames[i]:release()
      originFrames[i] = nil
    end
  end
end
function addChildAndRelease(node,subNode)
  node:addChild(subNode)
  subNode:release()
  return node
end

function getStickerSampler(filepath,fps)
  local sp = KuruAnimationSampler.createFromPath(BASE_DIRECTORY..filepath,false,false)
  sp:setRepeatCount(0)
  sp:setFPS(fps)
  sp:play()

  return sp
end

function reset(scene)

end



function finalize(scene)
 
  
end




function addNodeAndRelease(scene, node)
    scene:addNode(node)
    node:release()
    return node
end



-- function createSegNode(snapshotNode)
--   local seg = KuruSegmentationNode.create()
--   seg:setSourceSampler(snapshotNode:getSnapshot())
--  -- seg:setDistortionNode(distortionNode)
--   --scene:addNode(seg)
--   --seg:release()
--   return seg
-- end

function createSegNode(snapshotNode)
  local seg = KuruSegmentationNode.create()
  seg:setSourceSampler(snapshotNode:getSnapshot())
  --seg:setDistortionNode(distortionNode)


------------------------------- normal seg -------------------------------


  local item = seg:getSegmetationItem()
  item.enableEdge = true
  item.outerEdgeRatio = 0.0
  item.edgeRatio = 0.0
  item.edgeColor = Vector4.create(0, 0, 0, 0)
  item.outerEdgeColor = Vector4.create(0, 0, 0, 0)
  item.edgeType = SegmentationItemEdgeType.OUTSIDE
  item.interSpaceRatio = 0
  item.textureType = SegmentationItemTextureType.FOREGROUND


-----------------------------------------------------------------------------------------


------------------------------- draw image sample on edge -------------------------------

  -- local item = seg:getSegmetationItem()
  -- item.imageEdge = true
  -- item.imageScale = imageScale
  -- item.imageSpacing = imageSpacing
  -- item.imageEdgeExpand = expandEdge
  -- item.imageRotateToEdgeNormal = rotateImage
  --
  -- for i = 1, #imageList do
  --     local shapeSampler = TextureSampler.create(BASE_DIRECTORY .. "ht/" .. imageList[i], false, false)
  --     shapeSampler:setWrapMode(TextureWrap.CLAMP, TextureWrap.CLAMP)
  --     seg:addEdgeSampler(shapeSampler)
  -- end

-----------------------------------------------------------------------------------------

--   - enableEdge : 외곽선 사용 여부
-- - outerEdgeRatio : 외곽선의 바깥쪽 선 비율 지정(edgeRatio의 값과 비교해서 비율별로 외곽선의 바깥쪽 선 비율과 안쪽선 비율을 조정한다.)
-- - edgeRatio : 외곽선의 안쪽 선 비율 지정(outerEdgeRatio의 값과 비교해서 비율별로 외곽선의 바깥쪽 선 비율과 안쪽선 비율을 조정한다.)
-- - edgeColor : 외곽선의 안쪽선 color 지정
-- - outerEdgeColor : 외곽선의 바깥쪽선 color 지정
-- - edgeType : 외곽선 그리는 영역을 세그영역 안쪽/바깥쪽 중 선택(SegmentationItemEdgeType.INSIDE, SegmentationItemEdgeType.OUTSIDE)
--
-- 3- 기타
-- - interSpaceRatio : 세그 영역을 줄이는 비율. 0이면 줄이지 않고 값이 클수록 세그영역이 줄어듦.
-- - textureType : 세그 texture 기준 지정. setSourceSampler로 지정한 텍스처를 전경/후경으로 사용할지 선택. (SegmentationItemTextureType.FOREGROUND, SegmentationItemTextureType.BACKGROUND)
-- - maskAlphaThreshold : 세그를 적용할 alpha threshold 값.

  return seg
end


function createBGNodeWithSampler(sampler) --Average，Darken
  local floatNode1 = KuruFloatingImageNode.createFromSampler(sampler,-1,-1,2,2,BlendMode.Normal)
  return floatNode1       
end
function getCurrentSnapshot(scene, bufferScale)
    local node = KuruSnapshotNode.create()
    scene:addNode(node)
    node:release()
    node:setFrameBufferScale(bufferScale, bufferScale)
    return node
end
function getFragmentShader(filePath)
  return KuruShaderFilterNode.createWithFragmentShaderFile(BASE_DIRECTORY .. filePath, true)
end